package com.yaolisheng.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * @author : yaols
 * Desc:
 * Date: 2022.12.28.17:15
 **/

@Slf4j
@Configuration
@EnableScheduling
public class TestTask {

    @Resource
    private ExecutorService asyncServiceExecutor;

    @Scheduled(fixedRate = 1000 * 30)
    public void start() {

        Map<String, List<String>> map = new HashMap<>();
        List<Future<Map<String, List<String>>>> list2 = getList2();
        list2.forEach(future -> {
            try {
                map.putAll(future.get());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        });

    }

    private List<Future<Map<String, List<String>>>> getList2() {
        List<Future<Map<String, List<String>>>> list1 = new Vector<>();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            int finalI1 = i;
            Future<Map<String, List<String>>> submit = asyncServiceExecutor.submit(() -> {
                List<Future<String>> list = getList(finalI1);
                List<String> stringList = getStringList(list);
                Map<String, List<String>> map = new HashMap<>();
                map.put(finalI + "", stringList);
                return map;
            });
            list1.add(submit);
        }
        return list1;
    }

    private static List<String> getStringList(List<Future<String>> alist) {
        List<String> list = new ArrayList<>();
        alist.forEach(future -> {
            try {
                list.add(future.get());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        });
        return list;
    }

    private List<Future<String>> getList(int d) {
        List<Future<String>> list = new Vector<>();
        for (int i = 0; i < 20; i++) {
            int finalI = i;
            Future<String> submit = asyncServiceExecutor.submit(() -> {
                return (Thread.currentThread().getName() +"d"+ "-" + finalI);
            });
            list.add(submit);
        }
        return list;

    }
}
